/**
 * 
 */
package com.EstateManager.Controller;



import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import javax.enterprise.inject.New;
import javax.json.Json;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.hibernate.HibernateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.EstateManager.Dao.AdminDao;
import com.EstateManager.Dao.EstateBasicInfoDao;
import com.EstateManager.Dao.EstateInfoCheckDao;
import com.EstateManager.Entity.Admin;
import com.EstateManager.Entity.Estatebasicinfo;
import com.EstateManager.Entity.Estateinfocheck;
import com.EstateManager.Entity.User;
import com.EstateManager.Utils.FactoryResult;
import com.EstateManager.Utils.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.deser.std.JacksonDeserializers;

/**
 * 创建时间 : 下午3:40:41
 * @author Yonggang Liu
 *
 * AdminController.java
 */
@Controller
@RequestMapping("admin")
public class AdminController {
	
	@Autowired
	private AdminDao adminDao;
	
	@Autowired
	private  EstateBasicInfoDao estateBasicInfoDao;
	
	@Autowired
	private EstateInfoCheckDao estateInfoCheckDao;
	
	/**
	 * 获取管理员登录页面
	 * method : get
	 * url: EstateManager/admin/login.do
	 * */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String AdminLogin() {
		return "Admin/login";
	}
	
	/**
	 * 管理员登录验证
	 * methoud : post
	 * url : EstateManager/admin/login.do
	 * @param password
	 * @param username
	 * @return result 
	 * 存入session {userName,userId}
	 * */
	@RequestMapping(value = "loginCheck", method = RequestMethod.POST)
	@ResponseBody
	public Result loginCheck(String password, String username, HttpServletRequest request){
		Result result;
		Admin admin = null;
		try {
			admin = adminDao.getAdminByUsername(username);
		} catch (Exception e) {
			e.printStackTrace(System.out);
			result = FactoryResult.getResult(FactoryResult.EXCEPTION, e, "系统错误");
		}
		if (admin == null || !admin.getPassword().equals(password)) {
			result = FactoryResult.getResult(FactoryResult.ERROR, null, "用户名或密码错误");
		}else {
			result = FactoryResult.getResult(FactoryResult.SUCCESS, null, "登录成功");
			request.getSession().setAttribute("userName", username);
			request.getSession().setAttribute("userId", admin.getId());
		}
		
		return result;
	}

	/**
	 * 返回管理员主页面
	 * url:EstateManager/admin/view-homepage.do
	 * method:get
	 * 
	 * */
	@RequestMapping(value = "view-homepage", method = RequestMethod.GET)
	public String homepage() {
		return "Admin/home";
	}
	
	/**
	 * 返回管理员信息修改页面
	 * url:EstateManager/admin/view-adminInfoManage.do
	 * method:get
	 * */
	@RequestMapping(value = "view-adminInfoManage", method = RequestMethod.GET)
	 public String adminInfoManager(HttpServletRequest request, HttpServletResponse response, Model model) {
		Admin admin = adminDao.get((Integer)request.getSession().getAttribute("userId"));
		model.addAttribute("admin", admin);
		return "Admin/adminInfoManager";
	}
	
	
	
	/**
	 * 检验昵称是否存在
	 * 访问路径: /EstateManager/admin/json-isNickNameExist.do
	 * method : post
	 * @param : param 昵称
	 * @return : {"info": "昵称已存在","status": "n","data": user,"code": 4000,"message": "昵称已存在"}
	 * 			 {"info": "昵称不存在","status": "y","data": "","code": 1000,"message": "昵称不存在"}
	 * */
	@RequestMapping(value = "json-isNickNameExist", method = RequestMethod.POST)
	@ResponseBody
	public Result isNickNameExist(HttpServletRequest request, String param){
		Admin admin = adminDao.getAdminByNickName(param);
		Result result;
		if (admin != null && admin.getId() != (int)request.getSession().getAttribute("userId")) {
			result = FactoryResult.getResult(FactoryResult.ERROR, null, "昵称已存在");
		}else {
			result = FactoryResult.getResult(FactoryResult.SUCCESS,null, "昵称可用");
		}
		return result;
	}

	/**
	 * 用户信息修改<br>
	 * Method : POST
	 * URL : /EstateManager/admin/json-adminInfoModify.do
	 * @param user 用户信息
	 * @return result {"code": 1000,"data": user, "info": "用户数据修改成功", "status": "y"}
	 * 				  {"code": 4000,"data": e, "info": "用户数据修改失败", "status": "n"}
	 * <br>
	 * 
	 * 
	 * */
	@SuppressWarnings("finally")
	@RequestMapping(value = "json-adminInfoModify", method = RequestMethod.POST)
	@ResponseBody
	public Result adminInfoModify(@ModelAttribute("admin") @Valid Admin admin){
		Result result;
		try {
			Admin adminOld = adminDao.get(admin.getId());
	
			admin.setPassword(adminOld.getPassword());
			admin.setWeight(adminOld.getWeight());
			adminDao.merge(admin);
			result = FactoryResult.getResult(FactoryResult.SUCCESS, null, "用户数据修改成功");
		} catch (HibernateException e) {
			result = FactoryResult.getResult(FactoryResult.EXCEPTION, e, "用户数据修改失败");
		} 
		return result;
	}
	
	/**
	 * 请求密码修改页面
	 * URL: /EstateManager/admin/view-passwordModify.do
	 * Method: GET
	 * */
	@RequestMapping(value = "view-passwordModify", method = RequestMethod.GET)
	public String passwordModifyView(){
		return "/Admin/PasswordModify";
	}
	
	/**
	 * 对密码进行修改
	 * URL : /EstateManager/admin/json-passwordModify.do
	 * Method : POST
	 * 
	 * @param oldPassword 原密码
	 * @param newPassword 新密码[需大于六位]
	 * 
	 * @return result 
	 * 
	 * */
	@RequestMapping(value = "json-passwordModify", method = RequestMethod.POST)
	@ResponseBody
	public Result passwordModify(HttpServletRequest request, String oldPassword, String newPassword) {
		
		int id = (int)request.getSession().getAttribute("userId");
		Result result;
 		Admin admin = adminDao.get(id);
		if (admin.getPassword().equals(oldPassword) && newPassword.length() >= 6) {
			admin.setPassword(newPassword);
			try {
				adminDao.merge(admin);
				result = FactoryResult.getResult(FactoryResult.SUCCESS, admin.getPassword(), "密码修改成功");
			} catch (HibernateException e) {
				result = FactoryResult.getResult(FactoryResult.EXCEPTION, e, "密码修改失败");
				e.printStackTrace(System.out);
			}
		}else {
			result = FactoryResult.getResult(FactoryResult.OTHERERROR, null, "输入信息有误[密码错误或新密码长度小于6位]");
		}
		return result;
	}
	
	/**
	 * 返回房產信息審核頁面
	 * url:/EstateManager/admin/view-estateInfoCheck.do
	 * methoud : get
	 * */
	@RequestMapping(value = "view-estateInfoCheck", method = RequestMethod.GET)
	public String estateInfoCheckView() {
		return "/Admin/estateInfoCheck";
	}
	
	/**
	 * 根據房產審核狀態返回房產基本信息數據列
	 * url:/EstateManager/admin/json-getPageEstateBaisicInfo.do
	 * methoud : post
	 * @param pageSize 每页数据量
	 * @param pageNum 第几页
	 * @param checkState 审核状态
	 * */
	@RequestMapping(value = "json-getPageEstateBaisicInfo", method = RequestMethod.POST)
	@ResponseBody
	public Result getPageEstateBaisicInfo(int pageSize, int pageNum, String checkState) {
		Result result;
		try {
			List<Estatebasicinfo> listInfo = estateBasicInfoDao.getListByEstateCheckState(checkState, pageSize, pageNum);
			for (Estatebasicinfo estatebasicinfo : listInfo) {
				
				
				estatebasicinfo.setUser((User)estatebasicinfo.getUser().clone());
				estatebasicinfo.getUser().setUsername("");
				estatebasicinfo.getUser().setPassword("");
			}
			result = FactoryResult.getResult(FactoryResult.SUCCESS,  JSON.toJSONString(listInfo, SerializerFeature.DisableCircularReferenceDetect) , "获取数据成功");
		} catch (Exception e) {
			e.printStackTrace(System.out);
			result = FactoryResult.getResult(FactoryResult.EXCEPTION, null, "系统异常");
		}
		return result;
	}
	
	
	/**
	 * 房产信息审核提交
	 * url : /EstateManager/admin/json-addEstateCheck.do
	 * method : post
	 * @param estatebasicinfo.id
	 * @param checkResult
	 * @param remaks
	 * 
	 * */
	@RequestMapping(value = "json-addEstateCheck", method = RequestMethod.POST)
	@ResponseBody
	public Result addEstateCheck(Estateinfocheck estateinfocheck ,HttpServletRequest request) {
		Result result;
		if (estateinfocheck.getCheckResult().equals(EstateBasicInfoDao.CHECKTYPE_NOPASS) || estateinfocheck.getCheckResult().equals(EstateBasicInfoDao.CHECKTYPE_PASS)) {
			try {
				Estatebasicinfo estatebasicinfo = estateBasicInfoDao.get(estateinfocheck.getEstatebasicinfo().getId());
				Admin admin = adminDao.get((Integer)request.getSession().getAttribute("userId"));
				estateinfocheck.setAdmin(admin);
				estateinfocheck.setCheckTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
				int id = estateInfoCheckDao.save(estateinfocheck);
				estatebasicinfo.setEstateInfoCheckState(estateinfocheck.getCheckResult());
				estateBasicInfoDao.update(estatebasicinfo);
				estateinfocheck.setId(id);
				result = FactoryResult.getResult(FactoryResult.SUCCESS, estateinfocheck, "审核信息提交成功");
			} catch (HibernateException e) {
				e.printStackTrace(System.out);
				result = FactoryResult.getResult(FactoryResult.EXCEPTION, e, "系统错误");
			}
			
		}else {
			result = FactoryResult.getResult(FactoryResult.ERROR, null, "审核结果不是系统定义值");
		}
		return result;
	}
	
	
	
	
	
	
}
